<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">异动配置工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f8f9fa;
        }

        .page-title h3 {
            margin: 0;
            color: #333;
            font-size: 24px;
            font-weight: 600;
        }

        .page-title p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }



        /* 悬浮添加按钮样式 */
        .floating-add-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            z-index: 1000;
            text-decoration: none;
        }

        .floating-add-btn:hover {
            transform: translateY(-3px) scale(1.05);
            box-shadow: 0 6px 20px rgba(40, 167, 69, 0.5);
            color: white;
            text-decoration: none;
        }

        .floating-add-btn svg {
            width: 24px;
            height: 24px;
            fill: white;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s;
            margin-right: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-danger {
            background: #dc3545;
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 14px;
        }

        /* 操作链接样式 */
        .action-links {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;
        }

        .action-link {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            border-bottom: 1px solid transparent;
        }

        .action-link:hover {
            color: #5a67d8;
            border-bottom-color: #5a67d8;
            text-decoration: none;
        }

        .action-link.delete-link {
            color: #dc3545;
        }

        .action-link.delete-link:hover {
            color: #c82333;
            border-bottom-color: #c82333;
        }

        .action-link.view-link {
            color: #28a745;
        }

        .action-link.view-link:hover {
            color: #218838;
            border-bottom-color: #218838;
        }

        /* 响应式处理 */
        @media (max-width: 768px) {
            .action-links {
                flex-direction: column;
                gap: 8px;
                align-items: center;
                justify-content: center;
            }

            .action-link {
                font-size: 13px;
            }
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .table th,
        .table td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #dee2e6;
            vertical-align: middle;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
        }

        .table tr:hover {
            background: #f8f9fa;
        }

        .table tbody tr {
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .table tbody tr:hover {
            background: #e3f2fd;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .stock-info-cell {
            display: flex;
            flex-direction: column;
            gap: 2px;
            align-items: center;
            justify-content: center;
        }

        .stock-code {
            font-size: 14px;
            font-weight: 600;
        }

        .stock-name {
            font-size: 12px;
            color: #666;
            line-height: 1.2;
        }

        .ratio-cell {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            font-size: 14px;
            font-weight: 500;
        }

        .rise-ratio {
            color: #dc3545;
            font-weight: 600;
        }

        .fall-ratio {
            color: #28a745;
            font-weight: 600;
        }

        .ratio-separator {
            color: #666;
            font-weight: normal;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-enabled {
            background: #d4edda;
            color: #155724;
        }

        .status-disabled {
            background: #f8d7da;
            color: #721c24;
        }

        .search-box {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: end;
            position: relative;
        }

        .search-box .form-group {
            margin-bottom: 0;
        }

        .search-box .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 12px;
            border: none;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            cursor: pointer;
            transition: transform 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
        }

        .search-box .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
        }

        .search-icon {
            width: 16px;
            height: 16px;
            fill: white;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .page-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .page-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .wechat-auth {
            background: #f8f9fa;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }

        .wechat-auth .btn {
            margin-top: 10px;
        }

        .footer {
            text-align: center;
            color: white;
            opacity: 0.8;
            margin-top: 30px;
            font-size: 14px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        /* 移动端优化样式 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
                max-width: 100%;
            }

            .header {
                margin-bottom: 20px;
            }

            .header h1 {
                font-size: 20px;
                margin-bottom: 5px;
            }

            .header p {
                font-size: 14px;
            }

            .card {
                padding: 15px;
                border-radius: 12px;
                margin-bottom: 15px;
            }

            /* 页面头部移动端优化 */
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
                padding-bottom: 15px;
            }

            .page-title h3 {
                font-size: 20px;
            }

            .page-title p {
                font-size: 13px;
            }


            /* 搜索区域移动端优化 */
            .search-box {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 8px;
                margin-bottom: 15px;
                border: 1px solid #e9ecef;
            }

            .search-box .form-group {
                margin-bottom: 12px;
            }

            .search-box .form-group:last-child {
                margin-bottom: 0;
            }

            .search-box label {
                font-size: 13px;
                margin-bottom: 5px;
                color: #666;
            }

            .search-box input,
            .search-box select {
                padding: 10px;
                font-size: 16px; /* 防止iOS缩放 */
                border: 1px solid #ddd;
                border-radius: 6px;
            }

            .search-box .btn {
                width: 36px;
                height: 36px;
                margin-top: 0;
                margin-left: auto;
                padding: 8px;
                font-size: 14px;
                border-radius: 50%;
                align-self: flex-end;
            }

            .form-row {
                flex-direction: column;
                gap: 0;
            }

            /* 表格移动端优化 */
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                border-radius: 8px;
                border: 1px solid #dee2e6;
            }

            .table {
                font-size: 12px;
                min-width: 500px; /* 减少最小宽度，因为合并了列 */
            }

            /* 移动端涨跌比例样式优化 */
            .ratio-cell {
                flex-direction: column;
                gap: 2px;
                font-size: 12px;
                align-items: center;
                justify-content: center;
            }

            .ratio-separator {
                display: none; /* 移动端隐藏分隔符 */
            }

            .table th,
            .table td {
                padding: 8px 6px;
                white-space: nowrap;
            }

            .table th {
                background: #667eea;
                color: white;
                font-size: 11px;
                font-weight: 600;
            }

            /* 状态标签移动端优化 */
            .status-badge {
                font-size: 10px;
                padding: 2px 6px;
            }

            /* 操作按钮移动端优化 */
            .action-buttons {
                flex-direction: row;
                gap: 4px;
                justify-content: center;
            }

            .btn-edit, .btn-delete, .btn-view {
                padding: 4px 8px;
                font-size: 10px;
                border-radius: 12px;
                min-width: auto;
            }

            /* 分页移动端优化 */
            .pagination {
                gap: 5px;
                margin-top: 15px;
                flex-wrap: wrap;
                justify-content: center;
            }

            .page-btn {
                padding: 8px 12px;
                font-size: 14px;
                min-width: 40px;
            }



            /* 表单移动端优化 */
            .form-group input,
            .form-group select,
            .form-group textarea {
                font-size: 16px; /* 防止iOS缩放 */
                padding: 12px;
            }

            /* 微信授权区域移动端优化 */
            .wechat-auth {
                padding: 15px;
                margin-bottom: 15px;
            }

            .wechat-auth h4 {
                font-size: 16px;
                margin-bottom: 8px;
            }

            .wechat-auth p {
                font-size: 13px;
                margin-bottom: 10px;
            }

            /* 悬浮添加按钮移动端优化 */
            .floating-add-btn {
                width: 48px;
                height: 48px;
                bottom: 15px;
                right: 15px;
                box-shadow: 0 3px 10px rgba(40, 167, 69, 0.4);
            }

            .floating-add-btn:hover {
                transform: translateY(-2px) scale(1.05);
                box-shadow: 0 5px 15px rgba(40, 167, 69, 0.5);
            }

            .floating-add-btn svg {
                width: 20px;
                height: 20px;
            }
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            animation: fadeIn 0.3s;
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: none;
            border-radius: 12px;
            width: 80%;
            max-width: 400px;
            position: relative;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.3s;
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 15px;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
        }

        .modal-body {
            padding: 10px 0;
            color: #666;
            line-height: 1.5;
        }

        .modal-footer {
            text-align: right;
            margin-top: 20px;
        }

        .modal-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 20px;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .modal-btn:hover {
            transform: translateY(-2px);
        }

        .modal-btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }

        .modal-btn-secondary {
            background: #6c757d;
            margin-right: 10px;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 移动端弹窗优化 */
        @media (max-width: 768px) {
            .modal-content {
                width: 90%;
                margin: 20% auto;
                padding: 20px 15px;
            }

            .modal-title {
                font-size: 16px;
            }

            .close {
                font-size: 24px;
            }
        }

        /* 超小屏幕优化 */
        @media (max-width: 480px) {
            .container {
                padding: 8px;
            }

            .card {
                padding: 12px;
            }

            .header h1 {
                font-size: 18px;
            }

            .search-box {
                padding: 12px;
            }

            .table {
                font-size: 11px;
                min-width: 500px;
            }

            .table th,
            .table td {
                padding: 6px 4px;
            }

            .action-buttons {
                flex-direction: column;
                gap: 3px;
            }

            .btn-edit, .btn-delete, .btn-view {
                width: 100%;
                padding: 6px 8px;
                font-size: 11px;
            }

            .modal-content {
                width: 95%;
                margin: 10% auto;
                padding: 15px;
            }

            /* 悬浮添加按钮超小屏幕优化 */
            .floating-add-btn {
                width: 44px;
                height: 44px;
                bottom: 12px;
                right: 12px;
            }

            .floating-add-btn svg {
                width: 18px;
                height: 18px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 th:text="${title}">异动配置工具</h1>
            <p th:text="${description}">股票异动提醒配置工具，帮您监控股票价格异常变动</p>
        </div>

        <div class="card">

            <!-- 消息提示区域 -->
            <div id="message-area"></div>

            <!-- 微信授权登录区域 -->
            <div id="wechat-auth-area" class="wechat-auth" th:if="${openid == null or #strings.isEmpty(openid)}">
                <h4>微信消息推送授权</h4>
                <p>为了更好地为您提供股票异动提醒服务，请先进行微信授权</p>
                <button class="btn" onclick="goToWechatAuth()">
                    <i class="fas fa-weixin"></i>
                    获取微信授权登录
                </button>
            </div>

            <!-- 配置列表 -->
            <div id="config-list-container">
                <div class="search-box">
                    <div class="form-group">
                        <label>股票代码</label>
                        <input type="text" id="search-stock-code" placeholder="请输入股票代码" th:value="${stockCode}">
                    </div>
                    <div class="form-group">
                        <label>股票名称</label>
                        <input type="text" id="search-stock-name" placeholder="请输入股票名称" th:value="${stockName}">
                    </div>
                    <div class="form-group">
                        <label>状态</label>
                        <select id="search-status">
                            <option value="">全部</option>
                            <option value="1" th:selected="${status == '1'}">已启用</option>
                            <option value="0" th:selected="${status == '0'}">已关闭</option>
                        </select>
                    </div>
                    <button class="btn" onclick="searchConfigs()" title="搜索">
                        <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"></circle>
                            <path d="m21 21-4.35-4.35"></path>
                        </svg>
                    </button>
                </div>

                <div id="config-list">
                    <!-- 服务端渲染的配置列表 -->
                    <div th:if="${!isLoggedIn}" class="error">
                        请先登录后查看配置列表
                    </div>

                    <div th:if="${isLoggedIn and errorMessage != null}" class="error" th:text="${errorMessage}"></div>

                    <div th:if="${isLoggedIn and configList != null and !configList.empty}">
                        <div class="table-responsive">
                            <table class="table">
                            <thead>
                                <tr>
                                    <th>股票信息</th>
                                    <th>涨跌比例(%)</th>
                                    <th>推送频率(分钟)</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:each="config : ${configList}" th:data-config-id="${config.id}" onclick="editConfig(this.getAttribute('data-config-id'))">
                                    <td>
                                        <div class="stock-info-cell">
                                            <div class="stock-code">
                                                <a th:if="${config.stockCodes != null and !#strings.isEmpty(config.stockCodes)}"
                                                   th:href="@{/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA(stockCode=${#strings.contains(config.stockCodes, ',') ? #strings.substringBefore(config.stockCodes, ',') : config.stockCodes})}"
                                                   style="color: #667eea; text-decoration: none; font-weight: 600;"
                                                   th:text="${config.stockCodes}"
                                                   onclick="event.stopPropagation()">
                                                </a>
                                                <span th:unless="${config.stockCodes != null and !#strings.isEmpty(config.stockCodes)}" style="font-weight: 600;">-</span>
                                            </div>
                                            <div class="stock-name" th:text="${config.stockNames} ?: '-'" style="color: #666; font-size: 12px; margin-top: 2px;"></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="ratio-cell">
                                            <span th:if="${config.riseRatio != null}" class="rise-ratio" th:text="'+' + ${config.riseRatio}"></span>
                                            <span th:if="${config.riseRatio != null and config.fallRatio != null}" class="ratio-separator">/</span>
                                            <span th:if="${config.fallRatio != null}" class="fall-ratio" th:text="'-' + ${config.fallRatio}"></span>
                                            <span th:if="${config.riseRatio == null and config.fallRatio == null}">-</span>
                                        </div>
                                    </td>
                                    <td th:text="${config.pushFrequency} ?: '-'"></td>
                                    <td>
                                        <span th:class="'status-badge ' + (${config.alertEnabled} == 1 ? 'status-enabled' : 'status-disabled')"
                                              th:text="${config.alertEnabled} == 1 ? '已启用' : '已关闭'">
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-links">
                                            <a href="javascript:void(0)" class="action-link delete-link" th:data-config-id="${config.id}" onclick="deleteConfig(this.getAttribute('data-config-id')); event.stopPropagation();">删除</a>
                                            <a th:if="${config.stockCodes != null and !#strings.isEmpty(config.stockCodes)}"
                                               th:href="@{/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA(stockCode=${#strings.contains(config.stockCodes, ',') ? #strings.substringBefore(config.stockCodes, ',') : config.stockCodes})}"
                                               class="action-link view-link"
                                               onclick="event.stopPropagation();">查看异动</a>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        </div>
                    </div>

                    <div th:if="${isLoggedIn and (configList == null or configList.empty) and errorMessage == null}" class="no-data">
                        暂无配置数据
                    </div>
                </div>

                <div class="pagination" id="pagination">
                    <!-- 服务端渲染的分页 -->
                    <div th:if="${isLoggedIn and totalPages > 1}">
                        <button th:if="${currentPage > 1}" class="page-btn" th:data-page="${currentPage - 1}" onclick="changePage(this.getAttribute('data-page'))">上一页</button>

                        <th:block th:each="i : ${#numbers.sequence(T(java.lang.Math).max(1, currentPage - 2), T(java.lang.Math).min(totalPages, currentPage + 2))}">
                            <button th:if="${i == currentPage}" class="page-btn active" th:text="${i}"></button>
                            <button th:unless="${i == currentPage}" class="page-btn" th:data-page="${i}" onclick="changePage(this.getAttribute('data-page'))" th:text="${i}"></button>
                        </th:block>

                        <button th:if="${currentPage < totalPages}" class="page-btn" th:data-page="${currentPage + 1}" onclick="changePage(this.getAttribute('data-page'))">下一页</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer">
            <p>© 2025 Witmore AI - 让投资更智能</p>
        </div>
    </div>

    <!-- 悬浮添加按钮 -->
    <a href="/wechat/h5/config-edit/r6FisgH5ve7ylkCA" class="floating-add-btn" title="新建配置">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
    </a>

    <!-- 错误弹窗 -->
    <div id="errorModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">错误提示</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body" id="errorModalBody">
                <!-- 错误信息将在这里显示 -->
            </div>
            <div class="modal-footer">
                <button class="modal-btn" onclick="closeErrorModal()">确定</button>
            </div>
        </div>
    </div>

    <!-- 成功弹窗 -->
    <div id="successModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">成功提示</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body" id="successModalBody">
                <!-- 成功信息将在这里显示 -->
            </div>
            <div class="modal-footer">
                <button class="modal-btn" onclick="closeSuccessModal()">确定</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let currentOpenId = '';

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 页面初次加载时已有服务端渲染的数据，不需要再次AJAX加载
            // loadConfigList();
        });

        // 显示消息
        function showMessage(message, type = 'success') {
            if (type === 'error') {
                showErrorModal(message);
            } else {
                showSuccessModal(message);
            }
        }

        // 显示错误弹窗
        function showErrorModal(message) {
            const modal = document.getElementById('errorModal');
            const body = document.getElementById('errorModalBody');
            body.innerHTML = message;
            modal.style.display = 'block';
        }

        // 显示成功弹窗
        function showSuccessModal(message) {
            const modal = document.getElementById('successModal');
            const body = document.getElementById('successModalBody');
            body.innerHTML = message;
            modal.style.display = 'block';
        }

        // 关闭错误弹窗
        function closeErrorModal() {
            const modal = document.getElementById('errorModal');
            modal.style.display = 'none';
        }

        // 关闭成功弹窗
        function closeSuccessModal() {
            const modal = document.getElementById('successModal');
            modal.style.display = 'none';
        }

        // 弹窗外部点击关闭
        window.onclick = function(event) {
            const errorModal = document.getElementById('errorModal');
            const successModal = document.getElementById('successModal');
            if (event.target == errorModal) {
                errorModal.style.display = 'none';
            }
            if (event.target == successModal) {
                successModal.style.display = 'none';
            }
        }

        // 点击关闭按钮
        document.addEventListener('DOMContentLoaded', function() {
            // 为所有关闭按钮添加事件监听
            const closeButtons = document.querySelectorAll('.close');
            closeButtons.forEach(button => {
                button.onclick = function() {
                    const modal = this.closest('.modal');
                    modal.style.display = 'none';
                }
            });
        });

        // 加载配置列表
        function loadConfigList() {
            const stockCode = document.getElementById('search-stock-code')?.value || '';
            const stockName = document.getElementById('search-stock-name')?.value || '';
            const alertEnabled = document.getElementById('search-status')?.value || '';

            const queryData = {
                stockCode: stockCode,
                stockName: stockName,
                alertEnabled: alertEnabled === '' ? null : parseInt(alertEnabled),
                page: currentPage,
                size: pageSize
            };

            fetch('/api/wechat/stock-alert/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(queryData)
            })
            .then(response => {
                // 检查HTTP状态码
                if (response.status === 401) {
                    // 未登录，显示微信授权区域
                    showWechatAuthArea();
                    showMessage('请先进行微信授权登录', 'error');
                    return;
                }
                return response.json();
            })
            .then(result => {
                if (!result) return; // 如果是401跳转，result为undefined

                // 判断成功：code为成功码（通常是200或0）
                if (result.code === 200 || result.code === 0) {
                    // 构造前端期望的数据格式
                    const pageData = {
                        records: result.records,
                        total: result.page ? result.page.total : 0,
                        current: result.page ? result.page.current : 1,
                        size: result.page ? result.page.size : 10
                    };
                    renderConfigList(pageData);
                    renderPagination(pageData);
                } else {
                    // 检查是否是登录相关错误
                    if (result.code === 401) {
                        const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        window.location.href = redirectUrl;
                        return;
                    }
                    showMessage(result.message || '加载失败', 'error');
                }
            })
            .catch(error => {
                console.error('加载配置列表失败:', error);
                showMessage('网络错误，请稍后重试', 'error');
            });
        }

        // 渲染配置列表
        function renderConfigList(pageData) {
            const container = document.getElementById('config-list');

            if (!pageData.records || pageData.records.length === 0) {
                container.innerHTML = '<div class="loading">暂无配置数据</div>';
                return;
            }

            let html = `
                <div class="table-responsive">
                    <table class="table">
                    <thead>
                        <tr>
                            <th>股票信息</th>
                            <th>涨跌比例(%)</th>
                            <th>推送频率(分钟)</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            pageData.records.forEach(config => {
                // 处理股票代码，如果有多个代码，只取第一个用于跳转
                const stockCode = config.stockCodes ? config.stockCodes.split(',')[0].trim() : '';
                const stockCodeDisplay = config.stockCodes || '-';
                const stockCodeHtml = stockCode ?
                    `<a href="/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA?stockCode=${stockCode}" style="color: #667eea; text-decoration: none;">${stockCodeDisplay}</a>` :
                    stockCodeDisplay;

                // 处理股票代码链接的HTML，添加event.stopPropagation()
                const stockCodeHtmlWithStop = stockCode ?
                    `<a href="/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA?stockCode=${stockCode}" style="color: #667eea; text-decoration: none;" onclick="event.stopPropagation()">${stockCodeDisplay}</a>` :
                    stockCodeDisplay;

                // 构建股票信息HTML
                const stockInfoHtml = `
                    <div class="stock-info-cell">
                        <div class="stock-code">${stockCodeHtmlWithStop}</div>
                        <div class="stock-name" style="color: #666; font-size: 12px; margin-top: 2px;">${config.stockNames || '-'}</div>
                    </div>
                `;

                // 构建涨跌比例HTML
                let ratioHtml = '-';
                if (config.riseRatio || config.fallRatio) {
                    ratioHtml = '<div class="ratio-cell">';
                    if (config.riseRatio) {
                        ratioHtml += `<span class="rise-ratio">+${config.riseRatio}</span>`;
                    }
                    if (config.riseRatio && config.fallRatio) {
                        ratioHtml += '<span class="ratio-separator">/</span>';
                    }
                    if (config.fallRatio) {
                        ratioHtml += `<span class="fall-ratio">-${config.fallRatio}</span>`;
                    }
                    ratioHtml += '</div>';
                }

                html += `
                    <tr data-config-id="${config.id}" onclick="editConfig(${config.id})" style="cursor: pointer;">
                        <td>${stockInfoHtml}</td>
                        <td>${ratioHtml}</td>
                        <td>${config.pushFrequency || '-'}</td>
                        <td>
                            <span class="status-badge ${config.alertEnabled === 1 ? 'status-enabled' : 'status-disabled'}">
                                ${config.alertEnabled === 1 ? '已启用' : '已关闭'}
                            </span>
                        </td>
                        <td>
                            <div class="action-links">
                                <a href="javascript:void(0)" class="action-link delete-link" onclick="deleteConfig(${config.id}); event.stopPropagation();">删除</a>
                                <a href="/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA?stockCode=${stockCode}" class="action-link view-link" onclick="event.stopPropagation();">查看异动</a>
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            container.innerHTML = html;
        }

        // 渲染分页
        function renderPagination(pageData) {
            const container = document.getElementById('pagination');
            const totalPages = Math.ceil(pageData.total / pageSize);

            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }

            let html = '';

            // 上一页
            if (currentPage > 1) {
                html += `<button class="page-btn" onclick="changePage(${currentPage - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    html += `<button class="page-btn active">${i}</button>`;
                } else {
                    html += `<button class="page-btn" onclick="changePage(${i})">${i}</button>`;
                }
            }

            // 下一页
            if (currentPage < totalPages) {
                html += `<button class="page-btn" onclick="changePage(${currentPage + 1})">下一页</button>`;
            }

            container.innerHTML = html;
        }

        // 切换页码
        function changePage(page) {
            currentPage = parseInt(page);
            loadConfigList(); // 使用 AJAX 加载数据
        }

        // 搜索配置
        function searchConfigs() {
            currentPage = 1; // 搜索时重置到第一页
            loadConfigList(); // 使用 AJAX 加载数据
        }



        // 编辑配置
        function editConfig(id) {
            // 跳转到编辑页面
            window.location.href = `/wechat/h5/config-edit/r6FisgH5ve7ylkCA?id=${id}`;
        }

        // 删除配置
        function deleteConfig(id) {
            if (!confirm('确认删除此配置吗？')) {
                return;
            }

            fetch(`/api/wechat/stock-alert/delete/${id}`, {
                method: 'DELETE'
            })
            .then(response => {
                if (response.status === 401) {
                    showWechatAuthArea();
                    showMessage('请先进行微信授权登录', 'error');
                    return;
                }
                return response.json();
            })
            .then(result => {
                if (!result) return;

                if (result.code === 200 || result.code === 0) {
                    showMessage('删除成功', 'success');
                    setTimeout(() => {
                        // 重新加载页面以显示最新数据
                        window.location.reload();
                    }, 1000);
                } else {
                    if (result.code === 401) {
                        const redirectUrl = '/login/sms?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        window.location.href = redirectUrl;
                        return;
                    }
                    showMessage(result.message || '删除失败', 'error');
                }
            })
            .catch(error => {
                console.error('删除配置失败:', error);
                showMessage('网络错误，请稍后重试', 'error');
            });
        }



        // 跳转到异动记录页面
        function viewAbnormalRecord(stockCode) {
            if (stockCode) {
                window.location.href = `/wechat/h5/abnormal-record/r6FisgH5ve7ylkCA?stockCode=${stockCode}`;
            } else {
                showMessage('股票代码为空', 'error');
            }
        }

        // 跳转到微信授权页面
        function goToWechatAuth() {
            window.location.href = '/wechat/qrcode';
        }

        // 显示微信授权区域（当用户未登录时）
        function showWechatAuthArea() {
            const authArea = document.getElementById('wechat-auth-area');
            if (authArea) {
                authArea.style.display = 'block';
            }
        }

        // 隐藏微信授权区域
        function hideWechatAuthArea() {
            const authArea = document.getElementById('wechat-auth-area');
            if (authArea) {
                authArea.style.display = 'none';
            }
        }
    </script>
</body>
</html>
